package com.zhuhao.utils.reflect.demo;

import com.zhuhao.utils.reflect.MetaObject;
import com.zhuhao.utils.reflect.SystemMetaObject;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MetaObjectDemo2 {

    public static void main(String[] args) {
        // 创建一个示例对象
        User user = new User()
                .setId(1L)
                .setName("John Doe")
                .setAge(30);

        // 创建一个包含集合的复杂对象
        Order order = new Order()
                .setOrderId("ORD-2023001")
                .setUser(user);

        List<String> items = new ArrayList<>();
        items.add("Item 1");
        items.add("Item 2");
        order.setItems(items);

        Map<String, Object> details = new HashMap<>();
        details.put("paymentMethod", "Credit Card");
        details.put("discount", 10.0);
        order.setDetails(details);

        // 创建MetaObject
        MetaObject metaOrder = SystemMetaObject.forObject(order);

        // 使用MetaObject获取属性值
        System.out.println("获取简单属性: " + metaOrder.getValue("orderId"));
        System.out.println("获取嵌套属性: " + metaOrder.getValue("user.name"));
        System.out.println("获取集合元素: " + metaOrder.getValue("items[0]"));
        System.out.println("获取Map值: " + metaOrder.getValue("details.paymentMethod"));

        // 使用MetaObject设置属性值
        metaOrder.setValue("user.name", "Jane Smith");
        metaOrder.setValue("items[1]", "Updated Item 2");
        metaOrder.setValue("details.discount", 15.0);

        System.out.println("\n设置属性值后:");
        System.out.println("更新后的嵌套属性: " + metaOrder.getValue("user.name"));
        System.out.println("更新后的集合元素: " + metaOrder.getValue("items[1]"));
        System.out.println("更新后的Map值: " + metaOrder.getValue("details.discount"));

        // 检查属性是否存在
        System.out.println("\n属性存在检查:");
        System.out.println("user属性存在: " + metaOrder.hasGetter("user"));
        System.out.println("nonExistent属性存在: " + metaOrder.hasGetter("nonExistent"));

        // 获取属性类型
        System.out.println("\n属性类型:");
        System.out.println("user属性类型: " + metaOrder.getGetterType("user"));
        System.out.println("age属性类型: " + metaOrder.getGetterType("user.age"));
    }

    // 示例实体类
    @Data
    @Accessors(chain = true)
    static class User {
        private Long id;
        private String name;
        private Integer age;
    }

    @Data
    @Accessors(chain = true)
    static class Order {
        private String orderId;
        private User user;
        private List<String> items;
        private Map<String, Object> details;
    }
}
